package com.yanqu.road.server.cmd.union;

import com.yanqu.road.server.pb.UnionPb;
import com.yanqu.road.entity.enums.eUnionPosition;
import com.yanqu.road.entity.union.UnionMember;
import com.yanqu.road.pb.union.UnionProto;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.manger.union.UnionMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.utils.string.StringUtils;

//@Cmd(code = Protocol.S_UNION_POSITION_SET, desc = "设置职位")
public class SetPositionCmd extends AbstractCommand {

	private int position;

	private long operateUserId;

	@Override
	public boolean parseData(YanQuMessage packet) throws Exception {
		UnionProto.UnionPositionSetReqMsg reqMsg = UnionProto.UnionPositionSetReqMsg.parseFrom(packet.getBytes());
		position = reqMsg.getPosition();
		operateUserId = reqMsg.getUserId();
		return true;
	}

	@Override
	public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
		// 判断权限 族长 副族长才有权限
		String unionUid = player.getUserInfo().getUnionUid();
		if(StringUtils.isNullOrEmpty(unionUid)){
			ret = GameErrorCode.E_UNION_NO_JOIN_UNION;
			return;
		}
		UnionMember member = UnionMgr.getUnionMember(unionUid, player.getUserId());
		if(null == member){
			ret = GameErrorCode.E_UNION_NO_JOIN_UNION;
			return;
		}
		if (member.getPosition() == eUnionPosition.Master.getValue()
				|| member.getPosition() == eUnionPosition.DeputyMaster.getValue()) {
			ret = UnionMgr.setMemberPosition(player, operateUserId, position, false);
		} else {
			ret = GameErrorCode.E_UNION_POSITION_NO_ENOUGH;
		}
	}

	@Override
	public void sendData(GamePlayer player) {
		UnionProto.UnionPositionSetRespMsg.Builder respMsg = UnionProto.UnionPositionSetRespMsg.newBuilder();
		respMsg.setRet(ret);
		if(0 == ret){
			String unionUid = player.getUserInfo().getUnionUid();
			UnionMember member = UnionMgr.getUnionMember(unionUid, player.getUserId());
			UnionProto.UnionMemberTempMsg.Builder memberMsg = UnionPb.parseUnionMemberTempMsg(member);
			if(null != memberMsg){
				respMsg.setMember(memberMsg);
			}
		}
		player.sendPacket(Protocol.U_UNION_POSITION_SET, respMsg);
	}

}
